package com.sodaopen.study.controller;

import com.sodaopen.study.entity.AjaxResult;
import com.sodaopen.study.entity.User;
import com.sodaopen.study.service.ChapterService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/ajax")
public class AjaxController {

    @Autowired
    private ChapterService chapterService;

    @RequestMapping("/finishChapter")
    public Object finishChapter(Integer chapterId, HttpSession session) {

        AjaxResult result = new AjaxResult();
        User user = (User)session.getAttribute("loginUser");
        try {
            chapterService.finishChapter(user.getId(), chapterId);
            result.setSuccess(true);
        }catch (Exception e){
            e.printStackTrace();
            result.setSuccess(false);
        }

        return result;
    }


    @RequestMapping("/doCheckLocked")
    public Object doCheckLocked(Integer courseId, Integer chapterId, HttpSession session) {

        AjaxResult result = new AjaxResult();
        User user = (User)session.getAttribute("loginUser");
        try {
            Map map = chapterService.findLockedByPrimaryKey(user.getId(), courseId);
            if(map == null || map.get("chapter_id") == chapterId){  //map为空，没有锁
                result.setSuccess(true);
            }else{
                result.setSuccess(false);
            }

        }catch (Exception e){
            e.printStackTrace();
            result.setSuccess(false);
        }

        return result;
    }
}
